Exercise 6: Array Chunking

Directions

Given an array and chunk size, divide the array into many subarrays where each subarray is of length size

Examples

chunk([1, 2, 3, 4], 2) --> [[ 1, 2], [3, 4]]
chunk([1, 2, 3, 4, 5], 2) --> [[ 1, 2], [3, 4], [5]]
chunk([1, 2, 3, 4, 5, 6, 7, 8], 3) --> [[ 1, 2, 3], [4, 5, 6], [7, 8]]
chunk([1, 2, 3, 4, 5], 4) --> [[ 1, 2, 3, 4], [5]]
chunk([1, 2, 3, 4, 5], 10) --> [[ 1, 2, 3, 4, 5]]

Guidelines

Two solutions: 1. Iterative img

2. Use Array.prototype.slice() img

Solution

In [1]:
function chunk(array, size) {
  let chunked = [];
  let idx = 0;

  while (idx < array.length){
    chunked.push(array.slice(idx, size + idx));
    idx += size;
  }
  return chunked;
}

Alternative Solution

  • line 4: remember to -1
  • line 6: push a new chunk & add element in at the same time
In [2]:
function chunk(array, size) {
  let chunked = [];
  for (let element of array){
    let last = chunked[chunked.length - 1];
    if (!last || last.length === size){
      chunked.push([element]);
    } else {
      last.push(element);
    }
  }
  return chunked;
}
In [3]:
chunk([1, 2, 3, 4], 2)
Out[3]:
[ [ 1, 2 ], [ 3, 4 ] ]
In [4]:
chunk([1, 2, 3, 4, 5], 2)
Out[4]:
[ [ 1, 2 ], [ 3, 4 ], [ 5 ] ]
In [5]:
chunk([1, 2, 3, 4, 5, 6, 7, 8], 3)
Out[5]:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8 ] ]
In [6]:
chunk([1, 2, 3, 4, 5], 4)
Out[6]:
[ [ 1, 2, 3, 4 ], [ 5 ] ]
In [7]:
chunk([1, 2, 3, 4, 5], 10)
Out[7]:
[ [ 1, 2, 3, 4, 5 ] ]